import React from 'react'
import { Table,Icon,Modal,Popconfirm,Form,Input,Row,Col,DatePicker,Button,Message,Select} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
import api from '../../../api/advFamilyLockRelease';
import advApi from '../../../api/advRelease';
import officeApi from '../../../api/office';
import EditForm from '../../Form/AdvFamilyLockRelease';
import PageLog from '../../Form/AdFamilyPageLog';
import {uuid} from "../../../utils";

const { RangePicker } = DatePicker;
import moment from 'moment';

import PanelBox from '../../../components/PanelBox';
import {jsonToTree} from '../../../utils/tools'

import '../../../style/antd-theme.less';

export default class TablePage extends React.Component {
  state = {
    userSession:'',
    data: [],
    pagination: {
      pageSize:20,
      pageNum:1,
    },
    loading: false, 
    rowRecord:'',
    payment:{
      payMo:0,
      isOpen:false,
    },
    areaList:[],
    pageLog:{
      isOpen:false,
      logRowId:''
    },
    officeList:[]
  };
  columns = [{
    title: '广告标题',
    dataIndex: 'title',
  },{
    title: '消耗/总投放(次数)',
    dataIndex: 'totalCount',
    width: '13%',
    render:(text, record, index) =>  {
     return <span>{record.viewCount }/{record.totalCount}</span>
    },
  },{
    title: '支付金额',
    dataIndex: 'payMo',
    width: '7%',
  },{
    title: '状态',
    dataIndex: 'examState',
    width: '7%',
    render:(text, record, index) =>  {
      switch(record.examState){
        case 1:
          return '待审核';
        case 2:
         return '通过';
        case 3:
         return '拒绝';
        case 0:
         return '临时';
        default:
          return '未付款';
      }
    },
  },{
    title: '开始时间',
    dataIndex: 'startDate',
    width: '13%',
    
  },{
    title: '结束时间',
    dataIndex: 'endDate',
    width: '13%',
  },{
    title: '创建时间',
    dataIndex: 'createDate',
    width: '13%',
  }, {
    title: '操作',
    key: 'action',
    width: '15%',
    render: (text, record) => (
      <span>
        <a href="javascript:void(0)" onClick={this.edit.bind(this, record)}>详情</a>
        <span className="ant-divider" />
        {/*<Popconfirm title="您是否要删除该记录?" onConfirm={this.delete.bind(this, record.id)} okText="是" cancelText="否">
          <a href="javascript:void(0)">删除</a>
        </Popconfirm>
        <span className="ant-divider" />
        { record.payState == 1 ?
        <a href="javascript:void(0)" onClick={this.pay.bind(this, record)}>支付</a>
        : ''}*/}
        { record.examState == 2 ?
        <a href="javascript:void(0)" onClick={this.openPageLog.bind(this, record.id)}>观看日志</a>
        : ''}
      </span>
    ),
  }];

  handleTableChange = (pagination, filters, sorter) => {
    pagination.pageNum=pagination.current;
    this.setState({pagination});
   
    this.fetch({...pagination});
  }
  fetch = (params) => {
    this.setState({ loading: true });
    api.get('/advFamimlyLock/getAll', { params}).then((data) => {
      const _data = data.data.list;
      const pagination = { ...this.state.pagination };
      pagination.total = data.data.total;
      this.setState({
        loading: false,
        data: _data,
        pagination,
      });
    });
  }

  componentDidMount = () =>{
    let user =this.props.profile.user;
    this.setState({
      userSession:user
      });
    this.fetch({ ...this.state.pagination });
    this.getAllAreaList();
    this.getChildOffice(user);
  }

  add = () => {
    if(this.resetFields)this.resetFields();
    this.setState({
      isOpenModal: true,
      clearForm: false,
      titleName: '添加广告',
      rowRecord:false,
    });
  }
  edit = (record, event) => {
    if(this.resetFields)this.resetFields();
    Promise.all([this.getRowById(record.id)]).then(([record]) => {
      const _data = record;

      let timeDef="";
      if( record && record.startDate && record.endDate){
        timeDef=[moment(record.startDate , "YYYY-MM-DD HH:mm:ss"), moment(record.endDate, "YYYY-MM-DD HH:mm:ss")];
        _data.timeDef=timeDef;
      }

      if(record.logoPhotos){
        let photos=JSON.parse(record.logoPhotos);
        let pho=photos[0]
        let url=pho+"?process=image/resize,width_100,height_100";
        _data.logoImgUrl=url;
      }
     
      if(record.photos){
        let photos=JSON.parse(record.photos);
        let pho=photos[0]
        let url=pho+"?process=image/resize,width_150,height_150";
        _data.photoUrl=url;
      }

      let areaIds=record.areaIds;
      record.areaIdLists=[];
      record.areaIdsJson=[];
      let areaIdsJson=[];
      if(areaIds){
        areaIdsJson=JSON.parse('['+areaIds+']');
        let a='';
        for (let i = 0; i < areaIdsJson.length; i++) {
          a=a+'"'+areaIdsJson[i]+'",';
        }
        a=a.substring(0,a.length-1);
        areaIdsJson=JSON.parse('['+a+']');
      }
      let areaList=this.state.areaList;
      let areaIdLists=[];
      for (let i = 0; i < areaList.length; i++) {
        let val=areaList[i].title+areaList[i].description;
        if(val.indexOf('重庆')!=-1||(areaIds && areaIds.indexOf(areaList[i].key)!=-1)){
          areaIdLists.push(areaList[i]);
        }
        record.areaIdLists=areaIdLists;
        record.areaIdsJson=areaIdsJson;
      }

      _data.examState=2;
      this.setState({
        isOpenModal: true,
        clearForm: false,
        titleName: '查看广告/不可修改',
        rowRecord: _data 
      });
    });
    
  }

  getRowById = (id) => {
    return new Promise((resolve, reject) => {
      api.get('/adv/getFamLockAdvById', { id: id }).then((data) => {
        resolve(data.data);
      });
    });
  }

getAllAreaList = () => {
  api.get('/area/query_all_mini',{params: {typeMax:4,typeMin:4}} ).then((data) => {
    let areaList=data.data;
    const mockData = [];
    for (let i = 0; i < areaList.length; i++) {
      const data = {
        key: areaList[i].id,
        title: areaList[i].parentName,
        description: areaList[i].name,
      };
      
      mockData.push(data);
    }
    
    this.setState({ areaList:mockData});
  });

  } 
getChildOffice = (user) => {
  officeApi.get('/office/findAllOfficeByType',{
    parent_id:user.officeId,
    type:'1,2'
  }).then((data) => {
      let result=data.data;
      if(result.code==0){
        let list =result.data;
        let children=[];
        children.push(<Option key={user.officeId} >{user.officeName}</Option>);
        if(list){
          list.forEach(function(value, index, array) {
            children.push(<Option key={value.id} >{value.name}</Option>);
          })
        }
        this.setState({ officeList:children});
      }
    });
  } 

  pay = (record, event) => {
    advApi.get('/office/queryWallet',{} ).then((data) => {
      const result = data.data;
      if(result.code == 0){
        const payment=this.state.payment;
        payment.isOpen=true;
        payment.payMo=record.payMo;
        payment.id=record.id;
        payment.balance =result.data.balance;
        this.setState({payment});
       }else{
        Message.error(result.message);
       }
    });
    
  }
  
  delete = (id,event) => {
    api.delete('/advFamimlyLock/delete', {id:id}).then((data) => {
      const result= data.data;
     if(result.code == 0){
      Message.success('删除成功！');
      this.fetch({ ...this.state.pagination });
     }else{
      Message.error(result.message);
     }
    });
  }

  openPageLog = (id, event) => {
    let pageLog=this.state.pageLog;
    pageLog.isOpen=true;
    pageLog.logRowId=id;
    this.setState({pageLog});
    
  }
  pageLog={
    closeModal:()=>{
      const pageLog=this.state.pageLog;
      pageLog.isOpen=false;
      this.setState({pageLog});
    },
  }

  close = () => {
    this.setState({
      isOpenModal: false,
      clearForm: true,
    });
  }
  refeshData = () => {
    this.fetch({ ...this.state.pagination });
  }

  initChildrenParams = (params) => {
    this.resetFields = params.resetFields;
  }
  payment={
    closeModal:()=>{
      const payment=this.state.payment;
      payment.isOpen=false;
      this.setState({payment});
    },
    pay:(id, event) => {
      api.get('/adv/advFamimlyLock/pay',{params: {id:id}} ).then((data) => {
        const result = data.data;
        if(result.code == 0){
          Message.success('支付成功！');
          this.payment.closeModal();
          this.fetch({ ...this.state.pagination });
         }else{
          Message.error(result.message);
         }
      });
    },
  }

  render() {
    
    return (
      <div>
        <SearchForm searchCostState={this.state} goSearch={this.handleTableChange} create={this.add}/>
        <PanelBox>
          <Table columns={this.columns}  dataSource={this.state.data}  pagination={this.state.pagination}
            loading={this.state.loading}  onChange={this.handleTableChange}  rowKey='id' locale={{emptyText:'该代理商下暂无数据'}}
          />
        </PanelBox>
        <Modal
          title={this.state.titleName}
          visible={this.state.isOpenModal}
          onCancel={this.close}
          width={800}
          wrapClassName="vertical-center-modal"
          footer={null}
        >
          <EditForm areaList={this.state.areaList} userSession={this.state.userSession} rowRecord={this.state.rowRecord} pay={this.pay} close={this.close} refeshData={this.refeshData} clearForm={this.state.clearForm}  callbackParent={this.initChildrenParams}/>
        </Modal>
        <Modal
          title="支付"
          visible={this.state.payment.isOpen}
          onCancel={this.payment.closeModal}
          wrapClassName="vertical-center-modal"
          footer={null}
          >
          <div>
            <Row style={{marginBottom:'20px'}} ><Col style={{color:'red'}}>您应支付：{this.state.payment.payMo}元；</Col>&nbsp;&nbsp; <Col span={10}>(您的余额为：{this.state.payment.balance}元；)</Col></Row>
            <Button type="primary"  size="large" style={{marginRight:'10px'}}  onClick={this.payment.pay.bind(this,this.state.payment.id)} >支付</Button>
            <Button onClick={this.payment.closeModal}>稍后支付</Button>
          </div>
        </Modal>
        <Modal
          title='日志'
          visible={this.state.pageLog.isOpen}
          onCancel={this.pageLog.closeModal}
          width={800}
          wrapClassName="vertical-center-modal"
          onOk={this.pageLog.closeModal}
          okText="确认"
        >
          <PageLog rowId={this.state.pageLog.logRowId} close={this.pageLog.closeModal} />
        </Modal>
      </div>
    );
  }
}

    class SearchsForm extends React.Component {
      // 开始搜索
      goSearch = (e) => {
        let params=this.props.form.getFieldsValue().search;
        let _this=this.props;
        params.pageSize=_this.searchCostState.pagination.pageSize;
        params.pageNum =1;
        params.current =1;
        _this.goSearch(params);
     
      }

      srearchStyle = {
        labelCol: { span: 8},
        wrapperCol: { span: 16 },
      };
     
      render() {
        const { getFieldDecorator } = this.props.form;
        const {create } = this.props;
        const formItemLayout = this.srearchStyle;
        return <Form onSubmit={this.goSearch} layout="inline" style={{marginBottom:'10px'}}>
          <FormItem
          {...formItemLayout}
          style={{width:'300px'}}
            label="选择代理商"
          >
          {getFieldDecorator('search.officeId',{
            initialValue:this.props.searchCostState.userSession.officeId
          } )(
            <Select
              placeholder="选择代理商"
            >
            {this.props.searchCostState.officeList || []}
            </Select>
          )}
          </FormItem>
          <FormItem>
            <Button type="primary" icon="search" htmlType="submit">搜索</Button>
          </FormItem> 
          {/*
          <FormItem>
            <Button type="primary" icon="plus" onClick={create}>发布广告</Button>
          </FormItem>*/}
        </Form>
      }
    }
    const SearchForm = Form.create({})(SearchsForm);